import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { BusinessCircleService } from '../business-circle.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { defalutImg } from '../comm';
import { PermissionService } from '../../../service/permission.service';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-circle-manage',
  templateUrl: './circle-manage.component.html',
  styleUrls: ['./circle-manage.component.scss'],
  providers: [DatePipe]
})
export class CircleManageComponent implements OnInit {

  // seachForm
  seachForms: any = {
    state: '' // 状态 0 启用 1禁用 2删除
  }
  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  // 表格data
  tableData: any = [];
  defalutImg: string = defalutImg;

  // 弹窗
  isModelVisible: boolean = false;
  // ID输入提示
  inputIdtip: string = '';
  // modeltype 0：新增，1：编辑
  modelType: number = 0;
  // modelItem 单项data
  modeflItem: any = {};
  // 弹窗form表单
  validateForm!: FormGroup;
  // model loading
  isConfirmLoading: boolean = false;

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private services: BusinessCircleService,
    public permission: PermissionService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userId: ['', [Validators.required]], // 对应的用户id
      state: [''], // 圈子状态 0 正常 1禁封 2禁言
      identity: [''] // 身份标识 0 正常 1内部账号 2管理员
    });

    this.loadTable();
  }

  async loadTable() {
    try {
      this.tableForms.tableLoading = true;
      const res: any = await this.services.queryCircleManageTableData();
      this.tableForms.tableLoading = false;
      if (res.code == 0) {
        this.tableData = res.data || [];
      }
    } catch (error) {
      this.tableForms.tableLoading = false;
      this.tableData = [];
      // console.log(error);
    }
  }

  /**
   * openModel
   * 动态设置需验证项
   * @param num 0：封禁账号，1：设置身份
   */
  openModel(num: number) {
    if (num == 1) {
      this.validateForm.get('state')!.clearValidators();
      this.validateForm.get('state')!.markAsPristine();

      this.validateForm.get('identity')!.setValidators(Validators.required);
      this.validateForm.get('identity')!.markAsDirty();
    } else {
      this.validateForm.get('identity')!.clearValidators();
      this.validateForm.get('identity')!.markAsPristine();

      this.validateForm.get('state')!.setValidators(Validators.required);
      this.validateForm.get('state')!.markAsDirty();
    }

    this.validateForm.get('state')!.updateValueAndValidity();
    this.validateForm.get('identity')!.updateValueAndValidity();

    this.validateForm.reset();
    this.modelType = num;
    if (num == 0) {
      this.inputIdtip = '请输入要封禁的用户ID';
      // 默认设置禁言(注：暂仅保留禁言功能 2021/10/18)
      this.validateForm.get('state')?.setValue('2');
    } else {
      this.inputIdtip = '请输入要设置的用户ID';
    }
    this.isModelVisible = true;
  }
  // model确定
  handleOk(): void {
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return
    }
    for (let key in this.validateForm.value) {
      if (!this.validateForm.value[key]) {
        delete this.validateForm.value[key];
      }
    }
    
    if (this.modelType == 0) {
      let contentStr: string = this.validateForm.value['state'] == 1 ? '是否要禁用该用户的圈子权限，禁用后用户无法查看到商家圈子' : '是否要禁言该用户，禁言后该用户将无法发表动态和评论';
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: `<b style="color: red;">${ contentStr }</b>`,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.submitInterface();
        },
        nzCancelText: '取消',
        nzOnCancel: () => console.log('Cancel')
      });
    } else {
      this.submitInterface();
    }
  }
  // model取消
  handleCancel(): void {
    this.isModelVisible = false;
  }

  // 封禁、设置
  async submitInterface() {
    try {
      this.isConfirmLoading = true;
      const res: any = await this.services.setupBanData({...this.validateForm.value});
      this.isConfirmLoading = false;
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isModelVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error) {
      this.isConfirmLoading = false;
    }
  }

  /**
   * 取消禁言 || 取消管理员身份
   * @param item 
   * @param num 0：禁言 | 禁用，1：身份
   */
  async cancelSteup(item: any, num: number) {
    let params: any = {
      userId: item.userId
    }
    if (num == 0) {
      params.state = 0;
    } else {
      params.identity = 0;
    }

    try {
      const res: any = await this.services.setupBanData(params);
      if (res.code == 0) {
        this.message.success('取消成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '取消失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }
}
